package com.stox.charting.ui.swing.event.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.stox.charting.ui.swing.event.ChartModelChangedEvent;
import com.stox.charting.ui.swing.model.ChartModel.ChartModelListener;
import com.stox.charting.ui.swing.model.ChartSpan;
import com.stox.charting.ui.swing.model.price.PriceChartModel;
import com.stox.core.model.IBar;

public class ChartSpanChangedEventListener implements ChartModelListener {

	@Override
	@SuppressWarnings("unchecked")
	public void chartModelChanged(ChartModelChangedEvent event) {
		if(event.getProperty().equalsIgnoreCase("chartSpan")){
			PriceChartModel<IBar> model = (PriceChartModel<IBar>)event.getSource();
			if(model.getChartSpan().equals(ChartSpan.MAX)){
				model.setEventsEnabled(false);
				model.setMinimumBarSpanData(model.getBackupData());
				model.setEventsEnabled(true);
				model.fireChartModelChangedEvent("minimumSpanData");
			}else{
				List<IBar> backupData = model.getBackupData();
				Date currentDate = backupData.get(0).getDate();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(currentDate);
				calendar.add(model.getChartSpan().getUnit(), -1*model.getChartSpan().getMultiple());
		 		
				int index = 0;
				while(index < backupData.size() && backupData.get(index).getDate().after(calendar.getTime())){
					index++;
				}
				
				List<IBar> data = backupData.subList(0, index);
				model.setEventsEnabled(false);
				model.setMinimumBarSpanData(data);
				model.setEventsEnabled(true);
				model.fireChartModelChangedEvent("minimumSpanData");
			}
		}
	}
}